<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>参数列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <!-- closable属性决定是否可关闭，接受boolean，默认为true -->
            <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon :closable="false"></el-alert>
            <p>选择商品分类：
                <!-- 级联选择器通过options绑定数据 -->
                <!-- props里面是显示的规则 -->
                <el-cascader v-model="shoplistvalue" :options="shoplistoptions" :props="shoplistprops" @change="shoplistChange"></el-cascader>
            </p>
            <el-tabs v-model="activeName" @tab-click="handTableClick">
                <el-tab-pane label="动态参数" name="many">
                    <el-button type="primary" size="mini" :disabled="booel" @click="addparameterVisible=true">添加参数</el-button>
                    <el-table :data="manyData" style="width: 100%" border stripe> 
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="hendleClose(i,scope.row)">{{item}}</el-tag>
                                <el-input class="input-new-tag" v-if="scope.row.btninputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)"></el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index"></el-table-column>
                        <el-table-column prop="attr_name" label="参数名称"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button type="primary" size="mini" icon="el-icon-edit" @click="editfrom(scope.row)">编辑</el-button>
                                <el-button type="danger" size="mini" icon="el-icon-delete" @click="deletefrom(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="静态属性" name="only">
                    <el-button type="primary" size="mini" :disabled="booel" @click="addparameterVisible=true">添加属性</el-button>
                    <el-table :data="onlyData" style="width: 100%" border stripe>
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="hendleClose(i,scope.row)">{{item}}</el-tag>
                                <el-input class="input-new-tag" v-if="scope.row.btninputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)"></el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index"></el-table-column>
                        <el-table-column prop="attr_name" label="属性名称" min-width="700px"></el-table-column>
                        <el-table-column label="操作" min-width="700px">
                            <template slot-scope="scope">
                                <el-button type="primary" size="mini" icon="el-icon-edit" @click="editfrom(scope.row)">编辑</el-button>
                                <el-button type="danger" size="mini" icon="el-icon-delete" @click="deletefrom(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>
        <!--添加对话框  -->
        <el-dialog :title="'添加'+addparameter" :visible.sync="addparameterVisible" width="30%" @close="clearparameter">
            <el-form ref="parameterRef" :model="fparameterlist" :rules="parameterRules" label-width="100px">
                <el-form-item label="活动名称" prop="attr_name">
                    <el-input v-model="fparameterlist.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addparameterVisible = false">取 消</el-button>
                <el-button type="primary" @click="trueparameter">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 修改对话框 -->
        <el-dialog :title="'修改'+addparameter" :visible.sync="editparameterVisible" width="30%" @close="eaitclearparameter">
            <el-form ref="editparameterRef" :model="editlist" :rules="parameterRules" label-width="100px">
                <el-form-item :label="addparameter" prop="attr_name">
                    <el-input v-model="editlist.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editparameterVisible = false">取 消</el-button>
                <el-button type="primary" @click="editclass">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
    export default {
        data() {
            return {
                shoplistoptions:[],
                shoplistprops:{
                   expandTrigger: 'hover', 
                // 表示显示cat_name
                   label:'cat_name',
                   value:'cat_id',
                   children: 'children'
                },
                // v-model绑定的数据
                shoplistvalue:[],
                // 控制显示的页签activeName
                activeName:'many',
                // 控制按钮是否可以点击
                // booel: true
                // 动态参数数据
                manyData:[],
                // 静态属性参数数据
                onlyData:[],
                // 添加对话框是否显示
                addparameterVisible:false,
                fparameterlist:{
                    attr_name:''
                },
                parameterRules:{
                    attr_name:[
                        {required: true, message: '请输入参数', trigger: 'blur'}
                    ]
                },
                editparameterVisible:false,
                editlist:{
                    attr_name:''
                },
                parameterRules:{
                    attr_name:[
                        {required: true, message: '请输入参数', trigger: 'blur'}
                    ]
                },
                newid:{},
            }
        },
        // 生命周期函数
        created () {
            this.getshoplist()
        },
        methods: {
            // 商品分类列表
            async getshoplist() {
                const {data: res} = await this.$http.get('categories',{params:{type:3}})
                // console.log(res);
                if(res.meta.status !== 200)return this.$message.error(res.meta.mag)
                this.shoplistoptions = res.data
            },
            // 拿到级联选择器中的数据  v-model绑定的数据
            shoplistChange() {
                console.log(this.shoplistvalue);
                // 案例非让用计算属性 但是我觉得直接在这写比较简单
                // this.booel = false
                this.getcanshu()
            },
            // 此函数能打印出当前的页签显示
            handTableClick() {
                console.log(this.activeName);
                this.getcanshu()
            },
            // 获取参数函数
            async getcanshu() {
                // 为了防止选择的不是三级分类要判断v-model绑定的数据的length
                if(this.shoplistvalue.length !== 3){
                    this.shoplistvalue=[]
                    // 把table表格的数据也清空
                    this.manyData =[]
                    this.onilData =[]
                    return 
                }
                const {data: res} = await this.$http.get(`categories/${this.getID}/attributes`,{params:{sel:this.activeName}})
                // console.log(res);
                if(res.meta.status !== 200)return this.$message.error(res.meta.msg)
                
                // 在页面数据加载时处理数据
                res.data.forEach(item=>{
                    // 变成空格分割的数组
                    // split() 方法用于把一个字符串分割成字符串数组
                    // item.ttr_vals = item.attr_vals == ''?item.attr_vals.split(' '):[]
                    // push出错的原因是item.attr_vals是一个字符串 要把字符串转为数组
                    item.attr_vals = item.attr_vals.split('')
                    // console.log(res.data);
                    item.btninputVisible = false
                    item.inputValue = ''
                })
                if(this.activeName === 'many'){
                    this.manyData=res.data
                }else if(this.activeName === 'only') {
                    this.onlyData=res.data
                }
            },
            clearparameter() {
                this.$refs.parameterRef.resetFields()
            },
            trueparameter() {
                this.$refs.parameterRef.validate(async vail=>{
                    // console.log(vail);
                    if(!vail)return
                    const {data: res} = await this.$http.post(`categories/${this.getID}/attributes`,{
                        attr_name : this.fparameterlist.attr_name,
                        attr_sel : this.activeName
                    })
                    console.log(res);
                    if(res.meta.status !== 201)return this.$message.error(res.meta.msg)
                    this.$message.success('添加成功')
                    // this.getcanshu()
                    this.getcanshu()
                    this.addparameterVisible = false
                })
            },
            // 修改对话框
            // 点击编辑
            editfrom(roles) {
                // console.log(roles)
                this.newid = roles
                this.editlist.attr_name = roles.attr_name
                this.editparameterVisible = true
            },
            // 点击编辑的确定
            editclass() {
                this.$refs.editparameterRef.validate(async vali=>{
                    // console.log(vali)
                    if(!vali)return
                    const {data: res} = await this.$http.put(`categories/${this.getID}/attributes/${this.newid.attr_id}`,{
                        attr_name: this.editlist.attr_name,
                        attr_sel : this.activeName
                    })
                    // console.log(res)
                    if(res.meta.status !==200)return this.$message.error(res.meta.msg)
                    this.$message.success('修改成功')
                    this.getcanshu()
                    this.editparameterVisible = false
                })
            },
            // 清空编辑数据
            eaitclearparameter() {
                this.$refs.editparameterRef.resetFields()
            },
            // 删除
            async deletefrom(roles) {
                const res = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err=>err)
                // console.log(res);
                if(res !== 'confirm')return this.$message.info('已取消')
                const {data: str}=await this.$http.delete(`categories/${this.getID}/attributes/${roles.attr_id}`)
                // console.log(str);
                if(str.meta.status !== 200)return this.$message.error(str.meta.msg)
                this.$message.success('删除成功')
                this.getcanshu()
            },
            handleInputConfirm(row) {
                // 取到的数据去除首位空格的长度等不等于0
                if(row.inputValue.trim().length == 0){
                    row.inputValue = ''
                    row.btninputVisible = false
                    return
                }
                // row.attr_vals.push(row.inputValue.trim())
                // 把新的值push到每一行的数据里
                // row.attr_vals = row.attr_vals.split(' ')
                // console.log(row.attr_vals);
                row.attr_vals.push(row.inputValue.trim())
                // 先用push在页面添加数据 防止在数据库添加数据后刷新属性页面会合住
                row.inputValue = ''
                row.btninputVisible = false
                this.getsurrelist(row)
                
            },
            // 获取分类下的参数
            async getsurrelist(row) {
                const {data: res}= await this.$http.put(`categories/${this.getID}/attributes/${row.attr_id}`,{
                    attr_name:row.attr_name,
                    attr_sel:row.attr_sel,
                    attr_vals:row.attr_vals.join(' ')
                })
                // console.log(res);
                if(res.meta.status !== 200)return this.$message.error('添加属性失败')
                this.$message.success('修改属性成功')
            },
            showInput(roles) {
                // 当为true时页面上的值还没有被重新渲染 ，必须等渲染完成后再设置光标
                roles.btninputVisible = true
                // $nextTick当页面上元素被重新渲染之后，才会指定回调函数中的代码 ele规定
                this.$nextTick(_ => {
                // 让input输入框获取光标
                    this.$refs.saveTagInput.$refs.input.focus();
                });
            },
            // 关闭tag标签
            hendleClose(i,row) {
                // splice() 方法向/从数组中添加/删除项目，然后返回被删除的项目。
                row.attr_vals.splice(i,1)
                this.getsurrelist(row)
            }
        },
        // 计算属性
        computed: {
            // 控制按钮是否可以点击
            booel() {
                if(this.shoplistvalue.length !== 3){
                    return true
                }
                return false
            },
            // 拿到第三级的ID
            getID() {
                if(this.shoplistvalue.length == 3) {
                    return this.shoplistvalue[2]
                }
            },
            // 对话框标题
            addparameter() {
                if(this.activeName==='only'){
                    return '静态属性'
                }
                return '动态参数'
            }
        }
    }
</script>
<style lang="less" scoped>
.el-tag {
    margin: 10px
}
.input-new-tag {
    width: 150px;
}
</style>